package com.wulaobo.test;

import com.wulaobo.pojo.Event;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class StreamReduceDemo {

    public static void main(String[] args) throws Exception {

        //1.根据当前运行的上下文,获取正确的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.setRuntimeMode(RuntimeExecutionMode.BATCH);

        DataStreamSource<Event> dataSource = env.fromElements(
                new Event("Mary", "./home", 1000L),
                new Event("Bob", "./cart", 2000L),
                new Event("Jack", "./home", 3000L),
                new Event("Rose", "./order", 4000L),
                new Event("Joe", "./shoping", 5000L),
                new Event("Smith", "./product", 6000L));

        SingleOutputStreamOperator<Tuple2<String, Long>> mapOperator = dataSource.map(new MapFunction<Event, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(Event e) throws Exception {
                return Tuple2.of(e.user, 1L);
            }
        });

        mapOperator.print();

        mapOperator.keyBy(r -> true)// 为每一条数据分配同一个 key，将聚合结果发送到一条流中去
                .reduce(new ReduceFunction<Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> reduce(Tuple2<String, Long> value1,
                                                       Tuple2<String, Long> value2) throws Exception {
                        // 每到一条数据，用户 pv 的统计值加 1
                        return Tuple2.of(value2.f0, value1.f1 + value2.f1);
                    }
                }).print();

        env.execute();

    }

}
